﻿using System;
using System.Collections.Generic;
using System.Drawing;
using LevelEditor.Document;

namespace LevelEditor.View
{
    public class LayerView
    {
        #region Properties

        public Size Size { get; set; }

        public Layer Layer { get; set; }

        private List<Rectangle> DestinationRectangles { get; set; }

        #endregion

        #region Constructors

        public LayerView(Layer layer)
        {
            if (layer == null)
                throw new NullReferenceException();
            Layer = layer;
            Reset();
        }

        #endregion

        ~LayerView()
        {
        }

        #region Methods

        public void CheckSize()
        {
            Size = Layer.Size;
        }

        public void Reset()
        {
            // Resize tile lists
            CheckSize();
            DestinationRectangles = new List<Rectangle>(Layer.Tiles.Count);
            for(int i = 0; i < Layer.Tiles.Count; ++i)
            {
                Point tileLocation = new Point(i % Layer.Size.Width, i / Layer.Size.Width);
                DestinationRectangles.Add(new Rectangle(tileLocation.X * Layer.TileSet.TileSize.Width,
                    tileLocation.Y * Layer.TileSet.TileSize.Height, Layer.TileSet.TileSize.Width,
                    Layer.TileSet.TileSize.Height));
            }
        }

        public void CheckTiles()
        {
            Reset();
        }

        public void Draw(Graphics g)
        {
            //for (int x = 0; x < Size.Width; ++x)
            //{
            //    for (int y = 0; y < Size.Height; ++y)
            //    {
            //        Rectangle destRectangle = new Rectangle(x * Layer.TileSize.Width, y * Layer.TileSize.Height, 
            //            Layer.TileSize.Width, Layer.TileSize.Height);
            //        if(g.IsVisible(destRectangle))
            //            g.DrawImage(TileSetImages[Layer.TilesOld[x][y].TileSetIndex], 
            //                destRectangle, GetPaletteSourceRectFromTile(Layer.TilesOld[x][y]), 
            //                GraphicsUnit.Pixel);
            //    }
            //}
            if (Layer.TileSet.Image == null) Layer.TileSet.LoadImage();
            for (int i = 0; i < Layer.Tiles.Count; ++i)
            {
                if (g.IsVisible(DestinationRectangles[i]))
                    g.DrawImage(Layer.TileSet.Image, DestinationRectangles[i],
                        Layer.TileSet.GetSourceRectangleForTileValue(Layer.Tiles[i]), 
                        GraphicsUnit.Pixel);
            }
        }

        #endregion
    }
}
